<template>
  <div class="employees-container">
    <div class="app-container">
      <pageTools>
        <template #left>
          <span>总记录数据：{{ total }}</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            @click="exportToExcel"
          >导出excel </el-button>
          <el-button
            v-allow="'add'"

            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </pageTools>

      <el-card style="margin-top: 10px">
        <!-- 用:data=''绑定数据 -->
        <el-table
          border
          :data="list"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="用户头像">
            <template #default="{ row }">
              <img :src="row.staffPhoto" style="width: 100%">
            </template>
          </el-table-column>

          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <!-- default是固定写法 -->
            <template #default="{ row }">
              {{ formHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`employees/detail/${row.id}`)"
              >查看</el-button>

              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 一个弹窗组件 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addorEdit ref="myEmp" @success="hSuccess" />
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog title="分配角色" :visible.sync="assignshowDialog">
        <assignRole
          v-if="assignshowDialog"
          :user-id="userId"
          @success="assignshowDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import assignRole from '@/views/employees/assignRole.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addorEdit from './empDialog.vue'

// console.log(employeesEnum.hireType[0].value, 'employeesEnum')
// const hireType = {}

/* // 方式2进行提炼数据，避免多次遍历优化性能
employeesEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
console.log(hireType, 'hireType')

}) */

// 方式3
// 遍历方式第一次将空对象赋值给acc，每次调用返回值。最后用新的 变量接收，reduce写的：形参sum,item,参数回调与初始值
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

export default {
  components: {
    addorEdit, assignRole
  },
  data() {
    return {
      list: [],
      page: 1, // 页码值
      size: 5, // 每页显示数量
      total: 0,
      userId: '',
      showDialog: false,
      assignshowDialog: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 格式化聘用形式的数据
    formHireType(id) {
      // 此处id为形参是1 || 2
      // console.log(id, 'id')
      // const obj = employeesEnum.hireType.find(item => item.id == id) // 数据类型不同因此不可写全等
      // return obj ? obj.value : '未知'// 兜底检测，未知的提示未知
      return hireType[id] || '未知' // 方式2这样写只会执行一次优化了性能
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res, 'getEmployeeList')
        this.list = res.data.rows
        this.total = res.data.total
        // console.log(this.list, 'list.....')
      } catch (error) {
        console.log(error)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()
      console.log(`当前页: ${val}`)
    },
    hSuccess() {
      // 新增成功,总数++再发送请求，确保当前页数显示不下的时候我们重新发送数据并跳转到最后一页
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
    },
    hClose() {
      // 重置表单
      this.$refs.myEmp.restForm()
    },
    async hDel(id) {
      this.$confirm('您确认删除吗？')
        .then(async() => {
          const res = await delEmployee(id)
          if (this.list.length === 1) {
            // 如果当前数据删除没了，那么就是它的前一页发送数据
            this.page--
            if (this.page < 0) {
              this.page = 1
            }
          }
          if (res.code === 10000) {
            this.loadEmployeeList() // 删除成功则刷新页面
          }
        })
        .catch((error) => console.log(error))
    },
    hAssignRole(id) {
      this.userId = id
      this.assignshowDialog = true
    },

    exportToExcel() {
      const { tHeader, result } = this.transZhKeyToExcel(this.list)
      console.log(tHeader, 'tHeader')
      console.log(result, 'result')

      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },

    transZhKeyToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
      // 1 生成表头
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map((en_key) => {
        return mapInfo[en_key]
      })
      // 2 生成表的内容data
      const result = list.map((item) => {
        return Object.values(item)
      })
      return { tHeader, result }
    }
  }
}

</script>
<style lang="scss" scoped>
img{
  width: 50px;
}
</style>
